/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.arthurh.android.BdeInfo.connection;

import java.io.FileOutputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.ParserConfigurationException;
import java.io.InputStream;
import org.xml.sax.SAXException;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;
import java.io.FileInputStream;
import android.content.Context;
import android.widget.Toast;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.security.*;
import org.apache.http.protocol.HTTP;
import java.util.*;
import org.apache.http.client.HttpClient;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import org.xml.sax.InputSource;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;

/**
 *
 * @author arthur
 */
public class Connection {
    private String site = "http://mine-elite.fr/";
    public Connection() {
    }
    public boolean connSite(String pseudo, String pass, Context c) {
        pass = md5(pass);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("pseudo", pseudo));
        nameValuePairs.add(new BasicNameValuePair("pass", pass));
        String verif = md5(md5(pass) + md5(pseudo) + pseudo);
        
        String getVerif = this.connectionTo(nameValuePairs, "android.php").get(0);
        if (verif.trim().equals(getVerif.trim())) {
            this.WriteSettings(c, pseudo +":"+ verif);
            return true;
        }
        return false;
    }
    public boolean inscription(String prenom, String nom, String mail, String pseudo, String pass, Context c) {
        pass = md5(pass);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("pseudo", pseudo));
        nameValuePairs.add(new BasicNameValuePair("prenom", prenom));
        nameValuePairs.add(new BasicNameValuePair("nom", nom));
        nameValuePairs.add(new BasicNameValuePair("mail", mail));
        nameValuePairs.add(new BasicNameValuePair("pass", pass));
        String verif = md5(md5(pass) + md5(pseudo) + pseudo);
        String getVerif = this.connectionTo(nameValuePairs, "android.php").get(0);
        if(getVerif == null){
            return false;
        }
        if (verif.equals(getVerif)) {
            return true;
        }else{
            Toast.makeText(c, getVerif,Toast.LENGTH_SHORT).show(); 
        }
        return false;
    }
    public ArrayList getNewsStream(){
        SAXParserFactory fabrique = SAXParserFactory.newInstance();
        SAXParser parseur = null;
        ArrayList entries = null;
        try {
                
                parseur = fabrique.newSAXParser();
        } catch (ParserConfigurationException e) {
                e.printStackTrace();
        } catch (SAXException e) {
                e.printStackTrace();
        }
        // On défini l'url du fichier XML
        URL url = null;
        try {
                url = new URL("http://mine-elite.fr/android.php");
        } catch (MalformedURLException e1) {
                e1.printStackTrace();
        }
        DefaultHandler handler = new ReadXML();
        try {
            InputStream input = url.openStream();
            
            
            if(input==null)
                    Log.e("erreur android","null");
            else{
                Reader reader = new InputStreamReader(input,"ISO-8859-1");
 
                InputSource is = new InputSource(reader);
                is.setEncoding("ISO-8859-1");

                parseur.parse(is, handler);

                entries = ((ReadXML) handler).getData();
            }
        } catch (SAXException e) {
                e.printStackTrace();
        } catch (IOException e) {
                e.printStackTrace();
        }
        // On la retourne l'array list
        return entries;
    }
    public ArrayList<String> connectionTo(List<NameValuePair> nameValuePairs, String page) {
        HttpPost httppost = new HttpPost(site +page);
        
        httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        try {
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
        } catch (Exception e) {
            return null;
        }
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpResponse response = httpclient.execute(httppost);
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            boolean eof = false;
            String raw;
            ArrayList<String> content = new ArrayList<String>();
            while(!eof){
                raw = reader.readLine();
                if(raw != null && !raw.equals("")){
                    content.add(raw);
                }else{
                    eof = true;
                }
            }
            return content;
        } catch (Exception e) {
            return null;
        }

    }

    public void WriteSettings(Context context, String data) {
        FileOutputStream fOut = null;
        OutputStreamWriter osw = null;

        try {
            fOut = context.openFileOutput("info.dat", Context.MODE_PRIVATE);
            osw = new OutputStreamWriter(fOut);
            osw.write(data);
            osw.flush();
            //popup surgissant pour le résultat
            //Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show(); 
        } catch (Exception e) {
            //Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show(); 
        } finally {
            try {
                osw.close();
                fOut.close();
            } catch (IOException e) {
                //Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show(); 
            }
        }
    }

    public String ReadSettings(Context context) {
        FileInputStream fIn = null;
        InputStreamReader isr = null;

        char[] inputBuffer = new char[255];
        String data = null;

        try {
            fIn = context.openFileInput("info.dat");
            isr = new InputStreamReader(fIn);
            isr.read(inputBuffer);
            data = new String(inputBuffer);
            //affiche le contenu de mon fichier dans un popup surgissant

        } catch (Exception e) {
            return null;
        }
        data = data.trim();
        if (data.equals("")) {
            return null;
        }
        return data;
    }

    private String md5(String in) {

        MessageDigest digest;

        try {

            digest = MessageDigest.getInstance("MD5");

            digest.reset();

            digest.update(in.getBytes());

            byte[] a = digest.digest();

            int len = a.length;

            StringBuilder sb = new StringBuilder(len << 1);

            for (int i = 0; i < len; i++) {

                sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));

                sb.append(Character.forDigit(a[i] & 0x0f, 16));

            }

            return sb.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;

    }
}
